package com.hghivln.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hghivln.constants.Constants;
import com.hghivln.mapper.*;
import com.hghivln.pojo.domain.*;
import com.hghivln.pojo.dto.OrderChargeDto;
import com.hghivln.pojo.dto.OrderChargeFromDto;
import com.hghivln.pojo.dto.OrderChargeItemDto;
import com.hghivln.pojo.vo.AjaxResult;
import com.hghivln.service.OrderChargeService;
import com.hghivln.utils.IdGeneratorSnowflake;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Method;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.util.*;

@Service(methods = {
        @Method(name = "saveOrderAndItems",retries = 0,timeout = 6000)
})
public class OrderChargeServiceImpl implements OrderChargeService {

    @Autowired
    private OrderChargeMapper orderChargeMapper;

    @Autowired
    private OrderChargeItemMapper orderChargeItemMapper;

    @Autowired
    private CareHistoryMapper careHistoryMapper;

    @Autowired
    private CareOrderMapper careOrderMapper;

    @Autowired
    private CareOrderItemMapper careOrderItemMapper;

    /**
     * 根据挂号单号查询 病例信息
     * 根据病例单号查询 处方
     * 根据处方单号查询 处方详情
     */
    @Override
    public AjaxResult getNoChargeCareHistoryByRegId(String regId) {
        CareHistory careHistory = careHistoryMapper.selectCareHistoryByRegId(regId);
        if (ObjectUtils.isEmpty(careHistory)) {
            return AjaxResult.success("【" + regId + "】的挂号单没有对应的病例信息，请核对后再查询");
        } else {
            Map<String, Object> map = new HashMap<>();
            map.put("careHistory", careHistory);
            map.put("careOrders", Collections.EMPTY_LIST);
            List<Map<String, Object>> list = new ArrayList<>();
            List<CareOrder> careOrders = careOrderMapper.selectCareOrderListByChId(careHistory.getChId());
            if (CollectionUtil.isEmpty(careOrders)) {
                return AjaxResult.success("【" + regId + "】的挂号单没相关的处方信息，请核对后再查询");
            } else {
                for (CareOrder careOrder : careOrders) {
                    // 根据处方Id查询未支付的处方详情
                    List<CareOrderItem> careOrderItems = careOrderItemMapper.selectCareOrderItemListByCoId(careOrder.getCoId(), Constants.ORDER_STATUS_0);
                    //如果当前处方未支付的详情为空 结束当前循环
                    if (CollectionUtil.isEmpty(careOrderItems)) {
                        continue;
                    } else {
                        // 重新计算总价
                        BigDecimal allAmount = new BigDecimal("0");
                        for (CareOrderItem careOrderItem : careOrderItems) {
                            allAmount = allAmount.add(careOrderItem.getAmount());
                        }
                        Map<String, Object> careOrderMap = BeanUtil.beanToMap(careOrder);
                        careOrderMap.put("careOrderItems", careOrderItems);
                        careOrderMap.put("allAmount", allAmount);
                        list.add(careOrderMap);
                    }
                }
            }
            if (CollectionUtil.isEmpty(list)) {
                return AjaxResult.success("【" + regId + "】的挂号单没未支付的处方信息，请核对后再查询");
            } else {
                map.put("careOrders", list);
                return AjaxResult.success(map);
            }
        }
    }


    @Override
    public String saveOrderAndItems(OrderChargeFromDto orderChargeFromDto) {
        OrderChargeDto orderChargeDto = orderChargeFromDto.getOrderChargeDto();
        List<OrderChargeItemDto> orderChargeItemDtoList = orderChargeFromDto.getOrderChargeItemDtoList();
        OrderCharge orderCharge = new OrderCharge();
        BeanUtil.copyProperties(orderChargeDto, orderCharge);
        orderCharge.setCreateTime(DateUtil.date());
        orderCharge.setCreateBy(orderChargeFromDto.getSimpleUser().getUserName());
        orderCharge.setOrderId(IdGeneratorSnowflake.generatorIdWithProfix(Constants.ID_PROFIX_ODC));
        orderCharge.setOrderStatus(Constants.ORDER_STATUS_0);
        orderChargeMapper.insert(orderCharge);

        for (OrderChargeItemDto orderChargeItemDto : orderChargeItemDtoList) {
            OrderChargeItem orderChargeItem = new OrderChargeItem();
            BeanUtil.copyProperties(orderChargeItemDto, orderChargeItem);
            orderChargeItem.setOrderId(orderCharge.getOrderId());
            orderChargeItem.setStatus(Constants.ORDER_DETAILS_STATUS_0);
            orderChargeItemMapper.insert(orderChargeItem);
        }
        return orderCharge.getOrderId();
    }

    @Override
    public AjaxResult paySuccess(String orderId, String payType, String payPlatformId) {
        // 根据收费订单Id查询订单
        OrderCharge orderCharge = orderChargeMapper.selectById(orderId);
        if (ObjectUtils.isEmpty(orderCharge)) {
            return AjaxResult.fail("该收费订单不存在");
        } else {
            // 更新收费订单的状态
            orderCharge.setPayType(payType);
            orderCharge.setPayTime(DateUtil.date());
            orderCharge.setOrderStatus(Constants.ORDER_STATUS_1);
            orderCharge.setPayPlatformId(payPlatformId);
            orderChargeMapper.updateById(orderCharge);

            // 根据收费订单Id查询订单详情
            List<OrderChargeItem> orderChargeItemList = orderChargeItemMapper.selectByOrderId(orderId);
            if (CollectionUtil.isEmpty(orderChargeItemList)) {
                return AjaxResult.fail("该收费订单的收费详情为空");
            } else {
                List<String> itemIds = new ArrayList<>();
                for (OrderChargeItem orderChargeItem : orderChargeItemList) {
                    itemIds.add(orderChargeItem.getItemId());
                }
                // 更新收费详情的状态
                orderChargeItemMapper.updateByItemIds(itemIds,Constants.ORDER_DETAILS_STATUS_1);
                // 更新处方详情的状态
                careOrderItemMapper.updateByItemIds(itemIds,Constants.ORDER_DETAILS_STATUS_1);
            }
            return AjaxResult.success("创建订单并支付成功");
        }

    }

    @Override
    public OrderCharge queryOrderChargeByOrderId(String orderId) {
        return orderChargeMapper.selectById(orderId);
    }

    @Override
    public AjaxResult selectAllOrderChargeForPage(OrderChargeDto orderChargeDto) {
        List<String> orderIds = orderChargeItemMapper.selectOrderChargeItems();
        Page<OrderCharge> page = new Page<>(orderChargeDto.getPageNum(), orderChargeDto.getPageSize());
        QueryWrapper<OrderCharge> qw = new QueryWrapper<>();
        qw.like(StringUtils.isNotBlank(orderChargeDto.getPatientName()),OrderCharge.COL_PATIENT_NAME,orderChargeDto.getPatientName());
        qw.like(StringUtils.isNotBlank(orderChargeDto.getRegId()),OrderCharge.COL_REG_ID,orderChargeDto.getRegId());
        qw.in(CollectionUtil.isNotEmpty(orderIds),OrderCharge.COL_ORDER_ID,orderIds);
        this.orderChargeMapper.selectPage(page,qw);

        return AjaxResult.success("操作成功",page.getRecords(),page.getTotal());
    }

    @Override
    public AjaxResult selectOrderChargeItemByOrderId(String orderId) {
        QueryWrapper<OrderChargeItem> qw=new QueryWrapper<>();
        qw.eq(OrderChargeItem.COL_ORDER_ID,orderId);
        return AjaxResult.success(this.orderChargeItemMapper.selectList(qw));
    }

    @Override
    public OrderChargeItem queryOrderChargeItemByItemId(String itemId) {
        return orderChargeItemMapper.selectById(itemId);
    }
}

